﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Text;
using CoyoEden;
using CoyoEden.Models;

public partial class widgets_CategoryMenu_edit :WidgetEditBase
{
	#region base impementation
	public override void Save() {
		StringDictionary settings = GetSettings();
		StringBuilder selectedCategories = new StringBuilder();
		foreach (ListItem c in cblCategory.Items) {
			if (c.Selected == true) {
				selectedCategories.AppendFormat("{0}|", c.Value);
			}
		}
		if (selectedCategories.Length > 0) {
			selectedCategories.Remove(selectedCategories.Length - 1, 1);
		}
		settings["clist"] = selectedCategories.ToString();
		SaveSettings(settings);
	}
	protected override void OnPreRender(EventArgs e) {
		if (!Page.IsPostBack) {
			//load current settings
			StringDictionary settings = GetSettings();
			string[] selectedCategories = null;
			if (settings.ContainsKey("clist")) {
				selectedCategories = settings["clist"].Split('|');
			}
			//bind categories
			cblCategory.DataValueField = "Id";
			cblCategory.DataTextField = "Title";
			cblCategory.DataSource = CategoryList;
			cblCategory.DataBind();
			//reset selected categories
			if (null != selectedCategories) {
				ListItem tempItem = null;
				foreach (string c in selectedCategories) {
					tempItem = cblCategory.Items.FindByValue(c);
					if (tempItem != null) {
						tempItem.Selected = true;
					}
				}
			}
		}
		base.OnPreRender(e);
	}
	#endregion

	#region private fields
	private static readonly string CATEGORIESCACHEKEY = "CategoryListForMenu";
	private static List<Category> _CategoryList;
	private static object _SyncRoot = new object();
	private static List<Category> CategoryList {
		get {
			_CategoryList = HttpRuntime.Cache[CATEGORIESCACHEKEY] as List<Category>;
			if (_CategoryList == null) {
				lock (_SyncRoot) {
					if (null == _CategoryList) {
						_CategoryList = Category.TopCategories;
						HttpRuntime.Cache.Insert(CATEGORIESCACHEKEY, _CategoryList);
					}
				}
			}
			return _CategoryList;
		}
	}
	#endregion

	#region Category.Saved event subscribing
	static widgets_CategoryMenu_edit() {
		Category.Saved += new EventHandler<SavedEventArgs>(Category_Saved);
	}

	static void Category_Saved(object sender, SavedEventArgs e) {
		HttpRuntime.Cache.Remove(CATEGORIESCACHEKEY);
	}
	#endregion
}
